﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

/// <summary>
/// PageBase 的摘要说明
/// </summary>
public class PageBase : System.Web.UI.Page
{
    public PageBase()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
        this.Load += PageBase_Load;
    }
    /// <summary>
    /// 获取线程锁 对象
    /// </summary>
    /// <returns></returns>
    public static object get1 = new object();
    public static object get2 = new object();
    public static object get3 = new object();
    public static object get4 = new object();
    public static object set1 = new object();
    public static object set2 = new object();
    /// <summary>
    /// 将对象转化为json
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string ToJson(object obj)
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        string s = js.Serialize(obj);
        return s;
    }

    /// <summary>
    /// get参数转化为Hashtable  Content-Type: application/json;charset=UTF-8
    /// </summary>
    /// <returns></returns>
    public Hashtable getGetParamaters_json()
    {
        Hashtable h_sel = new Hashtable();
        string[] keys = Request.QueryString.AllKeys;
        for (int i = 0; i < keys.Length; i++)
        {
            h_sel[keys[i]] = Request.QueryString[keys[i]];
        }
        return h_sel;
    }
    /// <summary>
    /// post参数转化为Hashtable  Content-Type: application/json;charset=UTF-8
    /// </summary>
    /// <param name="postParameter"></param>
    public Hashtable getPostParameter_json()
    {
        //StreamReader sRead = new StreamReader(Request.InputStream);
        //Hashtable h_p = JsonToHashTable(sRead.ReadToEnd());
        //sRead.Close();
        //return h_p;
        Stream s = System.Web.HttpContext.Current.Request.InputStream;
        byte[] b = new byte[s.Length];
        s.Read(b, 0, (int)s.Length);
        string aa = Encoding.UTF8.GetString(b);
        Hashtable h_p = JSON.Decode(aa) as Hashtable;
        return h_p;
    }
    /// <summary>
    ///  post参数转化为Hashtable  Content-Type: application/x-www-form-urlencoded
    /// </summary>
    /// <returns></returns>
    public Hashtable getPostParamaters_form()
    {
        Hashtable h_sel = new Hashtable();
        string[] keys = Request.Form.AllKeys;
        for (int i = 0; i < keys.Length; i++)
        {
            h_sel[keys[i]] = Request.Form[keys[i]];
        }
        return h_sel;
    }

    public ResponseData isLogin()
    {
        ResponseData rd = new ResponseData();
        try
        {
            if (!new string[] { "Login", "Logout", "CheckLogin" }.Contains(Request["action"]))
            {
                //System.Collections.Specialized.NameValueCollection Headers = Request.Headers;
                object ScriptCloudToken = Request.Headers["token"];
                if (ScriptCloudToken != null && ScriptCloudToken.ToString() != "")
                {
                    string jiemi = DES.Decrypt(ScriptCloudToken.ToString());
                    string[] jiemiArr = jiemi.Split('|');
                    //jiemiArr[0]; 登录账号    jiemiArr[1]; 唯一标识
                    DateTime expirationTime = new TimeHelper().FormatTimeString(jiemiArr[2]);//token到期时间
                    DateTime currentTime = DateTime.Now;
                    int comparisonSize = DateTime.Compare(expirationTime, currentTime); //token到期时间与当前时间对比
                    if (comparisonSize > 0)
                    {
                        rd.message = "token验证通过";
                        rd.code = 1;
                    }
                    else
                    {
                        rd.message = "登录到期,请重新登录";
                        rd.code = 4;
                    }
                }
                else
                {
                    rd.message = "token不存在,请重新登录";
                    rd.code = 4;
                }
            }
            else
            {
                rd.message = "无需token";
                rd.code = 1;
            }
        }
        catch (Exception ex)
        {
            rd.code = 4;
            rd.message = "出错啦！错误详情：" + ex.Message;
            //string a = ex.HResult.ToString();
            //if (ex.HResult.ToString() == "-2146233033")
            //{
            //    rd.message = "出错啦！错误详情：登录到期,请重新登录";
            //}
        }
        return rd;
    }
    /// <summary>
    /// 当前登陆用户Hashtable信息
    /// </summary>
    public Hashtable CurrentLoginInfo()
    {
        Hashtable user = new Hashtable();
        object ScriptCloudToken = Request.Headers["token"];
        if (ScriptCloudToken != null && ScriptCloudToken.ToString() != "")
        {
            string jiemi = DES.Decrypt(ScriptCloudToken.ToString());
            string[] jiemiArr = jiemi.Split('|'); //jiemiArr[0]; 登录账号    jiemiArr[1]; 唯一标识    jiemiArr[2]; 到期时间
            user = new MemberUser().GetModel("loginNum", jiemiArr[0]);
        }
        return user;
    }

    void PageBase_Load(object sender, EventArgs e)
    {
        
    }


    /// <summary>
    /// 输出Json格式字符串
    /// </summary>
    /// <param name="data"></param>
    public void Json(object data)
    {
        Response.Write(JSON.Encode(data));
    }


    /// <summary>
    /// 直接输出文本，以防对方不会解析Json
    /// </summary>
    /// <param name="data"></param>
    public void Write(string data)
    {
        Response.Write(data);
    }


    public class ResponseData
    {
        /// <summary>
        /// 1：代表请求正常
        /// </summary>
        public int code { get; set; }
        public string message { get; set; }
        public object data { get; set; }
    }
    public class ResponseDataXM
    {
        /// <summary>
        /// 1：代表请求正常
        /// </summary>
        public int status { get; set; }
        public string message { get; set; }
        public object data { get; set; }
    }
    /// <summary>
    /// 菜单表响应数据
    /// </summary>
    public class ResponseData_Menu
    {
        /// <summary>
        /// 1：代表请求正常
        /// </summary>
        public int code { get; set; }
        public string msg { get; set; }
        public ArrayList data { get; set; }
        public int count { get; set; }
        public bool iss { get; set; }
        public string tip { get; set; }
    }
    /// <summary>
    /// 组织结构实体类
    /// </summary>
    public class deptclass
    {
        public string id { get; set; }
        public string Pid { get; set; }
        public string title { get; set; }
        public bool spread { get; set; }
        public List<deptclass> children { get; set; }
    }

    /// <summary>
    /// 常用时间格式
    /// </summary>
    /// <returns></returns>
    public string GetDateTimeString()
    {
        return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    }
    /// <summary>
    /// 短时间格式
    /// </summary>
    /// <returns></returns>
    public string GetDateTimeStringShort()
    {
        return DateTime.Now.ToString("yyyyMMddHHmmss");
    }
    /// <summary>
    /// 获取数据库时间
    /// </summary>
    /// <returns></returns>
    public DateTime GetSqlServerTime()
    {
        DateTime dt = Convert.ToDateTime(new SQLHelper("getnum").ExecuteScalar("select getdate() as ServerTime"));
        return dt;
    }
    /// <summary>
    /// DataTable转化为ArrayList
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public ArrayList DataTable2ArrayList(DataTable data)
    {
        ArrayList array = new ArrayList();
        for (int i = 0; i < data.Rows.Count; i++)
        {
            DataRow row = data.Rows[i];

            Hashtable record = new Hashtable();
            for (int j = 0; j < data.Columns.Count; j++)
            {
                object cellValue = row[j];
                if (cellValue.GetType() == typeof(DBNull))
                {
                    cellValue = null;
                }
                record[data.Columns[j].ColumnName] = cellValue;
            }
            array.Add(record);
        }
        return array;
    }
    /// <summary>
    /// Json 字符串 转换为 DataTable数据集合
    /// </summary>
    /// <param name="json"></param>
    /// <returns></returns>
    public static DataTable ToDataTableTwo(string json)
    {
        DataTable dataTable = new DataTable();  //实例化
        DataTable result;
        try
        {
            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            javaScriptSerializer.MaxJsonLength = int.MaxValue; //取得最大数值
            ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
            if (arrayList.Count > 0)
            {
                foreach (Dictionary<string, object> dictionary in arrayList)
                {
                    if (dictionary.Keys.Count == 0)
                    {
                        result = dataTable;
                        return result;
                    }
                    //Columns
                    if (dataTable.Columns.Count == 0)
                    {
                        foreach (string current in dictionary.Keys)
                        {
                            dataTable.Columns.Add(current, dictionary[current].GetType());
                        }
                    }
                    //Rows
                    DataRow dataRow = dataTable.NewRow();
                    foreach (string current in dictionary.Keys)
                    {
                        dataRow[current] = dictionary[current];
                    }
                    dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
                }
            }
        }
        catch
        {
        }
        result = dataTable;
        return result;
    }

    /// <summary>
    /// 处理json
    /// </summary>
    /// <param name="json">json字符串</param>
    /// <returns></returns>
    public Hashtable JsonToHashTable(string json)
    {
        Hashtable ht = new Hashtable();
        string jsonStr = json.Substring(1, json.Length - 2);//去掉首尾{}
        jsonStr = jsonStr.Replace("\"", "").Replace("'", "").Replace(" ", "");//去掉所有" '
        string[] jsonArr = SplitJson(jsonStr, ",");
        string str = null;

        for (int i = 0; i < jsonArr.Length; i++)
        {
            str = jsonArr[i];
            string[] arr = SplitJson(str, ":");
            //判断是否包含[ ]
            if (arr[1].Contains("["))//做数组处理
            {
                List<Hashtable> subHtl = JsonToHashTableList(arr[1]);
                ht.Add(arr[0], subHtl);
            }
            else if (arr[1].Contains("{"))//做json处理
            {
                Hashtable subHt = JsonToHashTable(arr[1]);
                ht.Add(arr[0], subHt);
            }
            else
            {
                ht.Add(arr[0], arr[1]);
            }
        }
        return ht;
    }

    /// <summary>
    /// 处理json数组
    /// </summary>
    /// <param name="json">json数组字符串</param>
    /// <returns></returns>
    private List<Hashtable> JsonToHashTableList(string json)
    {
        List<Hashtable> htl = new List<Hashtable>();
        string jsonStr = json.Substring(1, json.Length - 2);//去掉首尾[]
        string[] jsonArr = SplitJson(jsonStr, ",");
        for (int j = 0; j < jsonArr.Length; j++)
        {
            Hashtable ht = JsonToHashTable(jsonArr[j]);
            htl.Add(ht);
        }
        return htl;
    }

    /// <summary>
    /// 依据传入的符号分割字符串
    /// </summary>
    /// <param name="json"></param>
    /// <param name="code">冒号则只分割一次，逗号无视[],{}中的逗号分割</param>
    /// <returns></returns>
    private string[] SplitJson(string json, string code)
    {
        List<string> res = new List<string>();
        if (code == ",")
        {
            //无视[],{}中的逗号分割
            string pattern = @"(?<=\{|\[.*),(?=.*\}|\])";
            string result = System.Text.RegularExpressions.Regex.Replace(json, pattern, "####");//把[ ]和{ }中的逗号排除
            string[] arr = result.Split(',');
            string temp = null;
            for (int i = 0; i < arr.Length; i++)
            {
                temp = arr[i].Replace("####", ",");//恢复[ ]和{ }中的逗号
                res.Add(temp);
            }
        }
        else if (code == ":")
        {
            //冒号则只分割一次
            int index = json.IndexOf(code);
            res.Add(json.Substring(0, index));
            res.Add(json.Substring(index + 1, json.Length - index - 1));
        }
        return res.ToArray();
    }

}